package com.edu.juc.lock.readWriteLock;

import lombok.Data;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Data
public class MyCache {
    HashMap<String, String> map = new HashMap<>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, String value) {
        // 添加写锁
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 正在写操作...");
            TimeUnit.MILLISECONDS.sleep(300);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写操作完成。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public String get(String key) {
        String s = null;
        try {
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + " 正在读操作...");
            TimeUnit.MILLISECONDS.sleep(300);
            s = map.get(key);
            System.out.println(Thread.currentThread().getName() + " 读操作完成。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
        return s;
    }

}
